﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;

namespace WeFrame.AutoCode
{
    public partial class MainForm : Form
    {
        //变量定义
        string address;//数据库地址
        string userName;//数据用户名
        string password;//数据库密码
        string connectionString;//连接字符串



        string querySql;//查询语句
        MySqlConnection connection;//数据库连接
        MySqlCommand cmd;
        MySqlDataReader dr;
        ColumnEntity columnEntity;//列对象
        List<ColumnEntity> columnList;//列集合
        
        public MainForm()
        {
            InitializeComponent();
        }

        private void buttonConnectionTest_Click(object sender, EventArgs e)
        {

            //判断是否为空
            if (textBoxDatabaseAddress.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入数据库地址！");
                return;
            }

            if (textBoxDatabaseUserName.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入数据库用户名！");
                return;
            }
            if (textBoxDatabasePassword.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入数据库密码！");
                return;
            }

            //赋值
            address = textBoxDatabaseAddress.Text.Trim();
            userName = textBoxDatabaseUserName.Text.Trim();
            password = textBoxDatabasePassword.Text.Trim();

            
            //连接数据库

            connectionString = string.Format(" server={0}; initial catalog=information_schema;user id={1};password={2}", address, userName, password);
            connection = new MySqlConnection(connectionString);


            //测试数据库连接
            try
            {
                connection.Open();
                if (connection.State == ConnectionState.Open)
                {
                    MessageBox.Show("数据库连接成功！");
                }
                connection.Close();
            }
            catch(Exception ex)
            { 
                  MessageBox.Show("数据库连接失败！"+ex.Message);
            }


            //加载数据库列表
            querySql = "SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA` ORDER BY SCHEMA_NAME asc";



            try {
                connection.Open();
                cmd = new MySqlCommand(querySql, connection);
                dr = cmd.ExecuteReader();
                comboBoxDatabaseList.Items.Clear();
                while (dr.Read())
                {

                    comboBoxDatabaseList.Items.Add(dr.GetString(0));
                    
                }
                
               
                dr.Close();
                cmd.Dispose();
                connection.Close();
            }catch(Exception ex)
            {
                MessageBox.Show("加载数据库列表错误"+ex.Message);
            }
            comboBoxDatabaseList.SelectedIndex = comboBoxDatabaseList.Items.IndexOf("information_schema");
        }

        private void comboBoxDatabaseList_SelectedIndexChanged(object sender, EventArgs e)
        {

            querySql = @"select  TABLE_NAME,TABLE_COMMENT from information_schema.tables where table_schema='" + comboBoxDatabaseList.Items[comboBoxDatabaseList.SelectedIndex].ToString() + "' ORDER BY TABLE_NAME asc";
            connection.Open();
            cmd = new MySqlCommand(querySql, connection);
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "ds");
            da.Dispose();
            connection.Close();

            comboBoxTableList.DataSource = ds.Tables[0];
            comboBoxTableList.ValueMember = "TABLE_NAME";
            comboBoxTableList.DisplayMember = "TABLE_COMMENT";
    

        }

        private void buttonGenerateCode_Click(object sender, EventArgs e)
        {
            //构造表列对象

            querySql = @"SELECT 
                        COLUMN_NAME AS `列名`,
                        DATA_TYPE AS `数据类型`,
                        IFNULL(CHARACTER_MAXIMUM_LENGTH,0) AS `字符长度`,
                        CASE WHEN IS_NULLABLE='YES' THEN 1 ELSE 0 END  AS `是否允许非空`,
                        CASE WHEN EXTRA = 'auto_increment' THEN 1 ELSE 0 END AS `是否自增`,
                        CASE WHEN COLUMN_KEY = 'PRI' THEN 1 ELSE 0 END AS `是否是主键`,
                        IFNULL(COLUMN_COMMENT,'') AS `备注`,
                        IFNULL(COLUMN_DEFAULT,'') AS `默认值`
                        FROM information_schema.COLUMNS WHERE TABLE_NAME='" + comboBoxTableList.SelectedValue + "' AND TABLE_SCHEMA='" + comboBoxDatabaseList.Items[comboBoxDatabaseList.SelectedIndex].ToString() + "'";


            Console.WriteLine(comboBoxTableList.SelectedValue);
            Console.WriteLine(comboBoxTableList.SelectedText);
            //if (true) return;
            columnList = new List<ColumnEntity>();
            connection.Open();
            connection.ChangeDatabase(comboBoxDatabaseList.Items[comboBoxDatabaseList.SelectedIndex].ToString());
            cmd = new MySqlCommand(querySql, connection);
            dr = cmd.ExecuteReader();
            while(dr.Read()){
                columnEntity = new ColumnEntity();
                columnEntity.Name = dr.GetString(0);
                columnEntity.Type = dr.GetString(1);
                columnEntity.MaxLength = Convert.ToInt32(dr.GetValue(2));
                columnEntity.IsNull = Convert.ToBoolean(dr.GetValue(3));
                columnEntity.IsIdentity = Convert.ToBoolean(dr.GetValue(4));
                columnEntity.IsPrimaryKey = Convert.ToBoolean(dr.GetValue(5));
                columnEntity.Description = dr.GetString(6);
                columnEntity.DefaultValue = dr.GetString(7);
                columnList.Add(columnEntity);
            }
            dr.Close();
            connection.Close();
            //new FileHelper().WriteFile(".","entity1.txt",new EntityHelper().GenerateEntityText("CmsArticle",columnList)); 

            TableEntity tableEntity = new TableEntity();
            tableEntity.TableName = comboBoxTableList.SelectedValue.ToString();
            tableEntity.Description = comboBoxTableList.Text;
            ////Console.WriteLine("1::::::::" + comboBoxTableList.SelectedValue.ToString());
            //Console.WriteLine("2::::::::" + comboBoxTableList.Text);
            //Console.WriteLine("3::::::::" + comboBoxTableList.Items[comboBoxTableList.SelectedIndex]);

            //设置配置参数
            ConfigParameter configParameter = new ConfigParameter();
            configParameter.EntityTag = TextBoxEntity.Text;
            configParameter.DalTag = TextBoxDAL.Text;
            configParameter.BllTag = TextBoxBLL.Text;
            configParameter.NameSpaceTag = TextBoxNameSpace.Text;
            configParameter.DbHelperTag = TextBoxDBHelper.Text;


            FileHelper fileHelper = new FileHelper();
            EntityHelper entityHelper = new EntityHelper();
            UILHelper uilHelper = new UILHelper();
            DALHelper dalHelper = new DALHelper();
            BLLHelper bllHelper = new BLLHelper();

            tableEntity.InitialTableName = tableEntity.TableName;
            tableEntity.TableName = UtilsHelper.ToPascalCase(tableEntity.TableName);

            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + TextBoxEntity.Text + ".cs", entityHelper.GenerateEntityText(tableEntity, columnList,configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + TextBoxDAL.Text + ".cs", dalHelper.GenerateDALText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + TextBoxBLL.Text + ".cs", bllHelper.GenerateBLLText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "List.aspx", uilHelper.GenerateListAspxText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "List.aspx.cs", uilHelper.GenerateListAspxCsText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "List.aspx.designer.cs", uilHelper.GenerateListAspxDesignerCsText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "Edit.aspx", uilHelper.GenerateEditAspxText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "Edit.aspx.cs", uilHelper.GenerateEditAspxCsText(tableEntity, columnList, configParameter));
            fileHelper.WriteFile(TextBoxOutPath.Text, tableEntity.TableName + "Edit.aspx.designer.cs", uilHelper.GenerateEditAspxDesignerCsText(tableEntity, columnList, configParameter));

            MessageBox.Show("生成完成！");

        }

        private void ButtonOutputPath_Click(object sender, EventArgs e)
        {
            
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) 
            {
                TextBoxOutPath.Text = folderBrowserDialog1.SelectedPath;
            }
            
        }





    }
}
